import {createRouter, createWebHashHistory} from "vue-router";
import {useUserStore} from "@/store/sys/user";
import {commonRouters, dynamicRouters} from "./router.js";
import {useMenuStore} from "@/store/sys/menu";

/**
 * 动态新增路由
 * @param router
 * @param menus
 */
export const dynamicRouter = async (router, menus) => {
    if (menus && menus.length > 0) {
        for (let i = 0; i < menus.length; i++) {
            const menu = menus[i]
            if (!menu.children) {
                const routeComponent = dynamicRouters[menu.component]
                if (routeComponent) {
                    await router.addRoute('Home', {
                        name: menu.routerName,
                        path: menu.path,
                        component: routeComponent
                    })
                } else {
                    console.error(`路由 ${menu.component} 不存在, 请在 dynamicRouters 中添加`)
                }
            }
            await dynamicRouter(router, menu.children)
        }
    }
}

const router = createRouter({
    routes: commonRouters,
    history: createWebHashHistory()
})

router.beforeEach(async (to, from, next) => {
    if (to.path === '/login') {
        next()
        return
    } else {
        const userStore = useUserStore()
        if (!userStore.isAuthenticated) {
            next({name: 'Login'})
            return
        }
    }
    const menuStore = useMenuStore()
    if (!menuStore.initialized) {
        // 初始化菜单
        await menuStore.init(router)
        next({...to, replace: true})
        return
    }
    next()
})

export default router
